package com.wswy.wzcx.ui.car.remind

import android.app.Activity
import android.app.DatePickerDialog
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.car.CarTypeData
import com.wswy.wzcx.model.car.JZGCity
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.car.choose.ChooseCarActivity
import com.wswy.wzcx.ui.car.choose.ChooseCityActivity
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.utils.append0
import kotlinx.android.synthetic.main.fragment_add_valuation.*

/**
 * 添加估值
 */
class ValuationAddFragment : CBaseFragment() {

    companion object {
        private const val TAG = "ValuationAddFragment"
        private const val REQ_CODE_CHOOSE_CAR = 103
        private const val REQ_CODE_CHOOSE_CITY = 105
    }

    private lateinit var remindViewModel:RemindViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_add_valuation,container,false)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        v_choose_car_type.setUI("选择车型","请选择品牌车型")
        v_choose_reg_date.setUI("上牌时间","请选择上牌时间")
        v_input_mileage.setUI("行驶里程","请输入")
        v_choose_reg_city.setUI("选择城市","请选择上牌城市")

        remindViewModel = provideViewModelFromActivity(RemindViewModel::class.java)
        tv_car_no.text = remindViewModel.userCarInfo.carNo



        remindViewModel.userCarInfo.carExtendInfo?.run {

            remindViewModel.addValuationSaveChoose(carTypeData?.model?.id,
                    carTypeData?.getName(),
                    valuation?.registerLicenseDate,
                    valuation?.drivenDistance,
                    valuation?.registerLicenseCityId,
                    valuation?.registerLicenseCity)
        }

        updateInput()

        (v_input_mileage.chooseValue as? EditText)?.run {

            filters = arrayOf(InputFilter.LengthFilter(6))
            inputType = EditorInfo.TYPE_CLASS_NUMBER or EditorInfo.TYPE_NUMBER_FLAG_DECIMAL

        }

        //车辆选择
        v_choose_car_type.onClick {

            startActivityForResult(ChooseCarActivity.getStartIntent(it.context,null),REQ_CODE_CHOOSE_CAR)

        }
        //上牌时间
        v_choose_reg_date.onClick {
            showChooseDate(System.currentTimeMillis()){

                v_choose_reg_date.setSelectedValue(it)

                remindViewModel.addValuationSaveChoose(regDate = it)
            }
        }
        //选择城市
        v_choose_reg_city.onClick {

            startActivityForResult(ChooseCityActivity.startCityJZG(it.context),REQ_CODE_CHOOSE_CITY)
        }

        //保存
        btn_save.onClick {
            remindViewModel.addValuationSaveChoose(drivenDistance = v_input_mileage.getSelectedValue()?.toString())
            save()

        }
        val dialog = LoadingDialog(context,"请稍后")

        remindViewModel.getAddValuationLiveData().observe(this, Observer {
            it?.run {

                btn_save.isClickable = !inLoading()
                if(inLoading()){

                    dialog.show()
                }else{

                    if (isOk()){
                        dialog.setOnDismissListener {
                            (activity as? RemindActivity)?.run {
                                showInfo()
                            }
                        }
                        dialog.setSuccess("保存成功")
                        remindViewModel.setCarExtendInfo(data)

                    }else{
                        dialog.setSuccess("保存失败")
                    }
                }




            }
        })
    }

    private fun showChooseDate(maxDate:Long=0,block:((String)->Unit)) {

        var year=2018
        var month = 0
        var dayOfMonth = 1
        remindViewModel.addValuationStatus.getYMD()?.run {
            try {
                this[0]?.let {
                    year = it
                }
                this[1]?.let {

                    month = kotlin.math.max(0,it-1)
                }
                this[2]?.let {
                    dayOfMonth = it
                }
            } catch (e: Exception) {
            }
        }

        DialogFactory.createDatePickerDialog(context, { _, year, month, dayOfMonth ->

            block.invoke("$year-${(month+1).append0()}-${dayOfMonth.append0()}")

        }, year, month, dayOfMonth).run {
            //val datePicker = datePicker
            if (maxDate > 0){
                datePicker.maxDate = maxDate
            }

            show()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK){

            when(requestCode){
                REQ_CODE_CHOOSE_CAR -> {
                    //车辆选择
                    data?.getParcelableExtra<CarTypeData?>(Constants.EXTRA_DATA_CHOOSE_CAR)?.run {

                        model?.let {

                            v_choose_car_type.setSelectedValue(getName())

                            remindViewModel.addValuationSaveChoose(carModelId = it.id,
                                    carModelName = "${this.getName()}")

                        }

                    }
                }


                REQ_CODE_CHOOSE_CITY -> {
                    //城市选择
                    data?.getParcelableExtra<JZGCity?>(Constants.EXTRA_DATA_CHOOSE_CITY)?.run {

                        v_choose_reg_city.setSelectedValue(name)

                        remindViewModel.addValuationSaveChoose(regCityId = id,regCityName = name)

                    }

                }
            }


        }

    }

    private fun updateInput(){

        remindViewModel.addValuationStatus.run {

            if (!TextUtils.isEmpty(carModelId) && !TextUtils.isEmpty(carModelName)){
                v_choose_car_type.setSelectedValue(carModelName)
            }

            if (!TextUtils.isEmpty(regDate)){
                v_choose_reg_date.setSelectedValue(regDate)
            }

            if (!TextUtils.isEmpty(drivenDistance)){
                v_input_mileage.setSelectedValue(drivenDistance)
            }

            if (!TextUtils.isEmpty(regCityId) && !TextUtils.isEmpty(regCityName)){
                v_choose_reg_city.setSelectedValue(regCityName)
            }

        }

    }

    private fun save(){
        if (TextUtils.isEmpty(remindViewModel.addValuationStatus.carModelId)){
            ToastUtils.showText("请输选择车型")
            return
        }

        if (TextUtils.isEmpty(remindViewModel.addValuationStatus.regDate)){
            ToastUtils.showText("请选择上牌时间")
            return
        }

        if (TextUtils.isEmpty(remindViewModel.addValuationStatus.drivenDistance)) {
            ToastUtils.showText("请输入行使里程")
            return
        }

        if (TextUtils.isEmpty(remindViewModel.addValuationStatus.regCityId)) {
            ToastUtils.showText("请选择城市")
            return
        }

        remindViewModel.addValuation()

        StatTools.sendClick(context,StatisticsId.addvalue_save)

    }


}